package com.zhu.salesmanagement.network;

import com.dms2.salesmanagement.R;
import com.zhu.salesmanagement.SalesApplication;
import com.zhu.salesmanagement.common.Actions;
import com.zhu.salesmanagement.provider.SalesSettings;
import com.zhu.salesmanagement.utils.Util;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.graphics.drawable.AnimationDrawable;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * 上传门店数据
 */
public class PutCustomerData {

    public static final int SYNC_FAILEDEND = 0;
    public static final int SYNC_SUCCESSEND = 1;

    private static final int STTUP_PUTDTASKACTUALSC = 0; //业务主管上传实际拜访任务信息
    private static final int STTUP_PUTDTASKACTUALSHLEFSC = 1; //业务主管上传门店货架信息
    private static final int SETUP_PUTDTASKACTUALEXHIBITION = 2; //业务主管上传实际陈列考评信息request
    private static final int SETUP_PUTDTASKACTUALINTEGRATION = 3; //业务主管上传实际综合考评request
    private static final int SETUP_PUTDTASKACTUALIMPORTMSG = 4; //业务主管上传重要信息
    private static final int SETUP_PUTDTASKACTUALPHOTO = 5; //上传实际拜访照片 
    private static final int SETUP_PUTSTOREPROPERTY = 6; //上传门店特性调查信息

    private Context mContext = null;
    private Handler mHandler = null;
    private String mCustomerId = null;
    private CustomerShelfData mCustomerShelfData = null;
    private int mConnectStep = -1;
    private int retryCount = 0;
    private ViewGroup mParent = null;
    private View mPopView = null;
    private LayoutInflater mLayoutInflater = null;
    private ImageView mImageView = null;
    private TextView mTitleView = null;
    private View mAnimationView = null;
    private AnimationDrawable mAnimation = null;
    private boolean isSyncing = false;

    /**
     * 构造函数
     * @param context 上线文
     * @param mLayoutInflater LayoutInflater
     * @param handler 结果
     * @param parent 父ViewGroup
     */
    public PutCustomerData(Context context, LayoutInflater layoutInflater, Handler handler, ViewGroup parent){
        mContext = context;
        mHandler = handler;
        mParent = parent;
        mLayoutInflater = layoutInflater;
        mPopView = mLayoutInflater.inflate(R.layout.layout_popconnect, null);
        mPopView.setOnClickListener(null);

        setupView();
    }

    /**
     *设置界面 
     */
    private void setupView(){
        mImageView = (ImageView)(mPopView.findViewById(R.id.popconnect_animationImage));
        mTitleView = (TextView)(mPopView.findViewById(R.id.popconnect_title));
        mAnimationView = mPopView.findViewById(R.id.popconnect_animation);
    }

    /**
     * 显示联网界面
     */
    private void showView(String title){
        mTitleView.setText(title);
        mAnimation = (AnimationDrawable) mImageView.getBackground();
        mAnimation.setLevel(0);
        mAnimation.start();
        mParent.addView(mPopView);
    }

    /**
     * 移除联网界面
     */
    public void remoView(){
        mAnimation.stop();
        mAnimation = null;
        mParent.removeView(mPopView);
    }

    /**
     * 开始上传
     * @param cid 门店ID
     * @param title 门店名字
     */
    public void statSync(String cid, String title){
        mCustomerId = cid;
        if(mCustomerShelfData != null){
            mCustomerShelfData.destory();
            mCustomerShelfData = null;
        }
        mConnectStep = -1;
        showView(title);
        mCustomerShelfData = new CustomerShelfData(mContext, Util.mVerifyUserResult.id, Util.mVerifyUserResult.mUUID, cid);
        mCustomerShelfData.parseData();
        isSyncing = true;
        putDatingTaskActualSC();
    }

    /**
     * 联网重试
     */
    private void retryConnect(){
        switch(mConnectStep){
            case STTUP_PUTDTASKACTUALSC:
                putDatingTaskActualSC();
                break;
            case STTUP_PUTDTASKACTUALSHLEFSC:
                putCustomerShelf();
                break;
            case SETUP_PUTDTASKACTUALEXHIBITION:
                putDatingTaskActualExhibition();
                break;
            case SETUP_PUTDTASKACTUALINTEGRATION:
                putDatingTaskActualIntegration();
                break;
            case SETUP_PUTDTASKACTUALIMPORTMSG:
                putDatingTaskActualImportMsg();
                break;
            case SETUP_PUTDTASKACTUALPHOTO:
                putDatingTaskActualPhoto();
                break;
            case SETUP_PUTSTOREPROPERTY:
                putStoreProrery();
                break;
        }
    }

    /**
     * putDatingTaskActualSC
     */
    private void putDatingTaskActualSC() {
        mConnectStep = STTUP_PUTDTASKACTUALSC;
        Object[] object = mCustomerShelfData.getVisitedTaskObject();
        if (Actions.DEBUG) {
            Log.e("zhu", "putDatingTaskActualSC=" + object);
        }
        if (object == null) {
            putCustomerShelf();
            return;
        }
        PostMethod.postDatingTaskActual(object, new XMLRPCMethodCallback() {
            public void callFinished(int status, Object result) {
                boolean isSuccess = ParseData.parsePostData(result);
                if (isSuccess) {
                    retryCount = 0;
                    putCustomerShelf();
                } else {
                    syncFail();
                }
            }
        }, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * putCustomerShelf
     */
    private void putCustomerShelf(){
        mConnectStep = STTUP_PUTDTASKACTUALSHLEFSC;
        Object[] object = mCustomerShelfData.getShelfObject();
        if(Actions.DEBUG){
            Log.e("zhu","putCustomerShelf="+object);
        }
        if(object == null){
            putDatingTaskActualExhibition();
            return;
        }
        PostMethod.postCustomerShelf(object, new XMLRPCMethodCallback() {
                    public void callFinished(int status, Object result) {
                        boolean isSuccess = ParseData.parsePostData(result);
                        if(isSuccess){
                            retryCount = 0;
                            putDatingTaskActualExhibition();
                        }else{
                            syncFail();
                        }
                    }
                }, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * putDatingTaskActualExhibition
     */
    private void putDatingTaskActualExhibition(){
        mConnectStep = SETUP_PUTDTASKACTUALEXHIBITION;
        Object[] object = mCustomerShelfData.getCRCObject();
        if(Actions.DEBUG){
            Log.e("zhu","putDatingTaskActualExhibition="+object);
        }
        if(object == null){
            putDatingTaskActualIntegration();
            return;
        }
        PostMethod.putDatingTaskActualExhibition(object, new XMLRPCMethodCallback() {
                    public void callFinished(int status, Object result) {
                        boolean isSuccess = ParseData.parsePostData(result);
                        if(isSuccess){
                            retryCount = 0;
                            putDatingTaskActualIntegration();
                        }else{
                            syncFail();
                        }
                    }
                }, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * putDatingTaskActualIntegration
     */
    private void putDatingTaskActualIntegration(){
        mConnectStep = SETUP_PUTDTASKACTUALINTEGRATION;
        Object[] object = mCustomerShelfData.getCheckResultObject();
        if(Actions.DEBUG){
            Log.e("zhu","putDatingTaskActualIntegration="+object);
        }
        if(object == null){
            putDatingTaskActualImportMsg();
            return;
        }
        PostMethod.putDatingTaskActualIntegration(object, new XMLRPCMethodCallback() {
                    public void callFinished(int status, Object result) {
                        boolean isSuccess = ParseData.parsePostData(result);
                        if(isSuccess){
                            retryCount = 0;
                            putDatingTaskActualImportMsg();
                        }else{
                            syncFail();
                        }
                    }
                }, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * putDatingTaskActualImportMsg
     */
    private void putDatingTaskActualImportMsg(){
        mConnectStep = SETUP_PUTDTASKACTUALIMPORTMSG;
        Object[] object = mCustomerShelfData.getCheckImportMsgObject();
        if(Actions.DEBUG){
            Log.e("zhu","putDatingTaskActualImportMsg="+object);
        }
        if(object == null){
            putDatingTaskActualPhoto();
            return;
        }
        PostMethod.putDatingTaskActualImportMsg(object, new XMLRPCMethodCallback() {
                    public void callFinished(int status, Object result) {
                        boolean isSuccess = ParseData.parsePostData(result);
                        if(isSuccess){
                            retryCount = 0;
                            putDatingTaskActualPhoto();
                        }else{
                            syncFail();
                        }
                    }
                }, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * putDatingTaskActualPhoto
     */
    private void putDatingTaskActualPhoto(){
        mConnectStep = SETUP_PUTDTASKACTUALPHOTO;
        Object[] object = PostData.getStorePhotos(Util.mVerifyUserResult.id, Util.mVerifyUserResult.mUUID, mContext, mCustomerId);
        if(Actions.DEBUG){
            Log.e("zhu","putDatingTaskActualPhoto="+object);
        }
        if(object == null){
            putStoreProrery();
            return;
        }
        PostMethod.putDatingTaskActualPhoto(object, new XMLRPCMethodCallback() {
            public void callFinished(int status, Object result) {
                boolean isSuccess = ParseData.parsePostData(result);
                if(isSuccess){
                    retryCount = 0;
                    putStoreProrery();
                }else{
                    syncFail();
                }
            }
        }, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * putStoreProrery
     */
    private void putStoreProrery(){
        mConnectStep = SETUP_PUTSTOREPROPERTY;
        if(Actions.DEBUG){
            Log.e("zhu","putStoreProrery");
        }
        Object[] object = PostData.getStoreProperty(mContext, Util.mVerifyUserResult.id, Util.mVerifyUserResult.mUUID, mCustomerId);
        if(object == null){
            syncSuccessEnd();
            return;
        }
        PostMethod.postStoreProperty(object, new XMLRPCMethodCallback() {
            public void callFinished(int status, Object result) {
                boolean isSuccess = ParseData.parsePostData(result);
                if (isSuccess) {
                    retryCount = 0;
                    syncSuccessEnd();
                } else {
                    syncFail();
                }
            }
        }, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * 上传结束
     */
    private void syncSuccessEnd(){
        if(Actions.DEBUG){
            Log.e("zhu","syncSuccessEnd");
        }
        deletePutData();
        mConnectStep = -1;
        retryCount = 0;
        isSyncing = false;
        mHandler.sendEmptyMessage(SYNC_SUCCESSEND);
    }

    /**
     *上传失败 
     */
    private void syncFail(){
        if(Actions.DEBUG){
            Log.e("zhu","syncFail="+mConnectStep);
        }
        if(retryCount < 3){
            retryCount++;
            retryConnect();
        }else{
            retryCount = 0;
            mConnectStep = -1;
            isSyncing = false;
            mHandler.sendEmptyMessage(SYNC_FAILEDEND);
        }
    }

    /**
     * 清除上传后的数据
     */
    private void deletePutData(){
        ContentValues values = new ContentValues();
        values.put(SalesSettings.VisitedStoresColumns.DTASKACTUALID, "");
        values.put(SalesSettings.VisitedStoresColumns.CHECKIN_LAT, "");
        values.put(SalesSettings.VisitedStoresColumns.CHECKIN_LNG, "");
        values.put(SalesSettings.VisitedStoresColumns.CHECKIN_TIME, "");
        values.put(SalesSettings.VisitedStoresColumns.CHECKRESULT, "");
        values.put(SalesSettings.VisitedStoresColumns.CHECKRINFO, "");
        values.put(SalesSettings.VisitedStoresColumns.PUTSUCCESS, 1);
        values.put(SalesSettings.VisitedStoresColumns.PUTSTATUS, 0);
        String where = SalesSettings.VisitedStoresColumns.STOREID + " = \'" + mCustomerId + "\'";
        mContext.getContentResolver().update(SalesSettings.VisitedStoresColumns.CONTENT_URI, values, where, null);

        String where1 = SalesSettings.StoreCheckInfoColumns.STOREID + " = \'" + mCustomerId + "\'";
        mContext.getContentResolver().delete(SalesSettings.StoreCheckInfoColumns.CONTENT_URI, where1, null);

        String where2 = SalesSettings.StorePhotosColumns.STOREID + " = \'" + mCustomerId + "\'";
        mContext.getContentResolver().delete(SalesSettings.StorePhotosColumns.CONTENT_URI, where2, null);

        String where3 = SalesSettings.MyAddStoresColumns.STOREID + " = \'" + mCustomerId + "\'";
        mContext.getContentResolver().delete(SalesSettings.MyAddStoresColumns.CONTENT_URI, where3, null);

        String where4 = SalesSettings.StoreCheckInfoColumns.STOREID + " = \'" + mCustomerId + "\'" 
    			+ " AND " + SalesSettings.StoreCheckInfoColumns.DATATYPE +" = 1";
        mContext.getContentResolver().delete(SalesSettings.StoreCheckInfoColumns.CONTENT_URI, where4, null);

        mCustomerShelfData.updateSCImsg();
    }

    public boolean isSync(){
        return isSyncing;
    }

    /**
     * 数据销毁
     */
    public void destory(){
        mCustomerShelfData.destory();
        mCustomerShelfData = null;
        mAnimation = null;
        mPopView = null;
        mImageView = null;
    }
}
